/**
 * Created by netsnower on 16/3/15.
 */

var canvas, stage, exportRoot;
var count = 0;//loading百分比
var tipsTxt;//提示文本
var manifest, images;//图片加载列表
var isWap;
var loadingMc, loadingText;
var main, popMc, shareTips;

var audio_bg,audio_btn;
var reayAudio = false;
var firstPlay = true;
var isChecked = false;//是否检查了用户信息

var gameInterval;//滚动计时器
var score = 0;
var speed=0;
var initSpeed = 5;
var currentMap, newMap, gameMapCon,paizi,paiziCon,barrier,barrierCon;
var distance = 0;//行驶的距离
var isPause = true;//游戏是否暂停
//----------------------
var currentPaiziPoint = 0;//牌子数组指针
var oldPaiziPosition = 0;//前一个牌子位置
var paiziUnit;//牌子
var paiziUnitArray = [
    {name: "GamePaizi3", moved: true, interval: 2500},
    {name: "GamePaizi4", moved: true, interval: 2500},
    {name: "GamePaizi5", moved: true, interval: 2500},
    {name: "GamePaizi6", moved: true, interval: 2500},
    {name: "GamePaizi7", moved: true, interval: 2500},
    {name: "GamePaizi9", moved: true, interval: 3750},
    {name: "GamePaizi10", moved: true, interval: 3750}
];
var paiziCount = 0;//牌子总数


//----------------------
var currentMapArrPoint = 0;//地图数组指针
var oldMapPosition = 0;
var mapUnit = 0;//地图
var mapUnitArray = [
    {name: "Road2", interval: 1080},
    {name: "Road3", interval: 2100},
    {name: "Road1", interval: 2100},
    {name: "Road2", interval: 2100}
];
var mapCount = 0;//地图数组总数
var createGameMapCount = 0;//生成的地图总数

//------------------
//----------------------
var currentBarrierPoint = 0;//障碍数组指针
var oldBarrierPosition = 0;//前一个障碍位置
var barrierUnit;//障碍
var barrierUnitArray = [
    {name: "StopLine", moved: true, interval: 16050}
];
var barrierCount = 0;//障碍总数



//授权相关变量
var openid, openid_md5, nickname, sex, province, city, country, headimgurl;
var appname = 'LingDong325Game';//当前项目唯一标识，用来区分不同项目的cookie

//存储用户信息
var returnMyCustomer;
var returnWinningList, returnPrizeObj;
var salt;//后台返回的安全码
var closer_percent;//后台返回比你成绩好的人百分比
var testNow = false;

function init() {
    iniUiScale();
    //delInfo();
    if (testNow) {
        homeState = 'begin';
        openid = 'ddd';
        openid_md5 = '7e1fd4bdb71af39f722134e8b93fc799';
        nickname = '小明';
        sex = '1';
        province = '北京';
        city = '北京';
        country = 'CN';
        headimgurl = 'http://wx.qlogo.cn/mmopen/BA8GZZ2EGwVckE3zlfIdkibgctJ22eS2fWYoB4rzNvV4rpFSLPQtRkOdhGcKPLDdkOEqbcxk2WOq5ofmVHqEaIw/0';
        returnWinningList = [
            {
                "nickname": "我是一个小小草小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "12345678",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },{
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            },
            {
                "nickname": "小明",
                "gift_type": "1",
                "gift_name": "精美18:1领动汽车模型"
            }
        ];

        returnMyCustomer = {
            "customer_id": "1",
            "lottery_time_id": "1",
            "openid": "aaa",
            "nickname": "小明",
            "sex": "1",
            "province": "北京",
            "city": "北京",
            "country": "CN",
            "headimgurl": "http://www.relonline.cn/resource/relonline$1/logo.jpg",
            "lottery_times": "4",
            "total_lottery_times": "10",
            "rest_lottery_times": "6",
            "rest_speed_count": "4",
            "rest_double_count": "3",
            "gift_type": "1",
            "game_history_id": "0",
            "game_history_score_highest": "15",
            "game_history_score_highest_time": "2015-09-24 18:07:32",
            "customer_status": "0",
            "customer_time_create": "2015-09-24 18:07:10",
            "customer_time_lottery": "2015-09-24 18:08:09",
            "customer_time_lastmodified": "2015-09-24 21:05:48",
            "customer_name": "收货姓名",
            "customer_phone": "18220000000",
            "customer_address": "收地址"
        };

        initCjs();//测试使用
    } else {
        iniLogin();
    }
}
//授权，根据来路显示相应的界面
function iniLogin() {
    //alert(document.location.href);
    readInfo();
    if (openid != null) {
        //已经获得授权
        initCustomer();
    } else {
        //未授权
        //自动跳转到授权页面
        document.location.href = 'getopenid.php?gotourl=index.html&state=' + appname;
    }
}
//读取本地存储的用户信息，跳转到对应的画面
function readInfo() {
    openid = getCookie(appname + "_openid");
    openid_md5 = getCookie(appname + "_openid_md5");
    nickname = decodeURI(getCookie(appname + "_nickname"));
    sex = decodeURI(getCookie(appname + "_sex"));
    province = decodeURI(getCookie(appname + "_province"));
    city = decodeURI(getCookie(appname + "_city"));
    country = decodeURI(getCookie(appname + "_country"));
    headimgurl = decodeURIComponent(decodeURI(getCookie(appname + "_headimgurl")));
    if (String(headimgurl).indexOf('http') >= 0) {
        //shareImg=headimgurl;
    }
    //alert('openid='+openid+'\nopenid_md5='+openid_md5+'\nnickname='+nickname+'\nsex='+sex+'\nprovince='+province+'\ncity='+city+'\ncountry='+country+'\nheadimgurl='+headimgurl);
}
//删除cookie
function delInfo() {
    delCookie(appname + "_openid");
    delCookie(appname + "_openid_md5");
    delCookie(appname + "_nickname");
    delCookie(appname + "_sex");
    delCookie(appname + "_province");
    delCookie(appname + "_city");
    delCookie(appname + "_country");
    delCookie(appname + "_headimgurl");
    alert('cookies清除成功');
}
function iniBgSound() {
    var btnsound = new lib.BtnSound();
    btnsound.x = 570;
    btnsound.y = 10;
    btnsound.name='btn_audio_bg';
    stage.addChild(btnsound);
    btnsound.addEventListener('click', soundClickHandle);

    audio_bg = getEl('music_audio_bg');
    audio_bg.play();
    if (window.WeixinJSBridge) {
        WeixinJSBridge.invoke('getNetworkType', {}, function (e) {
            //alert('自动播放');
            if (firstPlay && audio_bg.currentTime == 0) {
                audio_bg.play();
                //home.btn_sound.visible=true;
                firstPlay = false;
            }
        });
    } else {
        document.addEventListener("WeixinJSBridgeReady", function () {
            WeixinJSBridge.invoke('getNetworkType', {}, function (e) {
                //alert('自动播放');
                if (firstPlay && audio_bg.currentTime == 0) {
                    audio_bg.play();
                    //home.btn_sound.visible=true;
                    firstPlay = false;
                }
            });
        }, false);

    }

    //背景音乐开关
    function soundClickHandle(evt) {
        if (checkPointID(evt)) {
            if (evt.currentTarget.currentFrame == 0) {
                evt.currentTarget.gotoAndStop(1);
                audio_bg.pause();
            } else {
                evt.currentTarget.gotoAndStop(0);
                audio_bg.play();
            }
        }
    }
}
//框架代码--------
function initCjs() {
    //audio_bg=getEl('music_audio_bg');
    //stageH = (640 / document.documentElement.clientWidth) * document.documentElement.clientHeight;
    canvas = getEl('mainCanvas');
    stage = new createjs.Stage(canvas);
    exportRoot = new lib.LingDong325Game();
    stage.addChild(exportRoot);
    stage.update();
    stage.enableMouseOver();

    createjs.Ticker.setFPS(lib.properties.fps);
    createjs.Ticker.addEventListener('tick', stage);
    preloading();
    //iniFps();
    iniWx();
}
//预载loading界面
function preloading() {
    //alert('预载');
    manifest = [
        {src: "images/loading1.png", id: "loading1"},
        {src: "images/loading2.png", id: "loading2"},
        {src: "images/loading3.png", id: "loading3"}
    ];

    var loader = new createjs.LoadQueue(false);
    //loader.installPlugin(createjs.Sound);
    loader.addEventListener('fileload', preloadingHandleFileLoad);
    loader.addEventListener('complete', preloadingHandleComplete);
    loader.loadManifest(manifest);
}
function preloadingHandleFileLoad(evt) {
    if (evt.item.type == 'image') {
        images[evt.item.id] = evt.result;
    }
}
function preloadingHandleComplete() {
    loading();
}
//loading
function loading() {
    loadingMc = new lib.LoadingMc();
    loadingMc.x = 0;
    exportRoot.addChild(loadingMc);

    images = images || {};
    var loader = new createjs.LoadQueue(false);
    //loader.installPlugin(createjs.Sound);
    loader.addEventListener('fileload', handleFileLoad);
    loader.addEventListener('complete', handleComplete);
    //loader.loadFile({src:"images/ShuangDan_atlas_.json", type:"spritesheet", id:"ShuangDan_atlas_"}, true);
    loader.loadManifest(lib.properties.manifest);
}
function handleFileLoad(evt) {
    if (evt.item.type == 'image') {
        images[evt.item.id] = evt.result;
    }
    count++;
    loadingMc.msg.text = (Math.floor(count / lib.properties.manifest.length * 100));
    loadingMc.bar.gotoAndStop(Math.floor(count / lib.properties.manifest.length * 100) - 1);
}

function handleComplete(evt) {
    iniHome();
    //iniBgSound();
}

//初始化首页-------
function iniHome() {
    checkDevice();
    iniEvent();
    //清除loading
    exportRoot.removeChild(loadingMc);
    loadingMc = null;
    iniGameMc();
}
function iniEvent() {
    if (createjs.Touch.isSupported()) {
        createjs.Touch.enable(stage);
    }
    //stage.addEventListener("stagemousedown", stagemousedownHandle);
}
function stagemousedownHandle(evt) {
    console.log('down');
    evt.preventDefault();
    if (firstPlay && audio_bg.currentTime == 0) {
        audio_bg.play();
        firstPlay = false;
    }
    stage.removeEventListener("stagemousedown", stagemousedownHandle);
}
//显示fps
function iniFps() {
    var fpsLabel = new createjs.Text("-- fps", "bold 18px Arial", "#ccc");
    stage.addChild(fpsLabel);
    fpsLabel.x = 10;
    fpsLabel.y = 20;
    fpsLabel.visible = true;
    fpsLabel.addEventListener('tick', fpsEnterFrameHandle);
    function fpsEnterFrameHandle(evt) {
        fpsLabel.text = Math.round(createjs.Ticker.getMeasuredFPS()) + " fps";
    }
}

//初始化游戏界面
function iniGameMc() {
    if (main) {
        exportRoot.removeChild(main);
        main = null;
    }
    main = new lib.GameMc();
    exportRoot.addChild(main);

    gameMapCon = main.road_con;
    mapCount = mapUnitArray.length;
    paiziCon = main.paizi_con;
    paiziCount = paiziUnitArray.length;
    barrierCon=main.barrier_con;
    barrierCount = barrierUnitArray.length;

    iniGameBeginBtn();
    iniGameMap();
    iniPaizi();
    if(checkUserInfo()==false && !isChecked){
        showInfoForm();
        isChecked=true;//检查过了，本次打开游戏时间内不再检查
    }
}
//检查用户信息，如用户已中奖但未填写姓名电话则返回false
function checkUserInfo(){
    if(parseInt(returnMyCustomer.gift_type)!=0 && returnMyCustomer.customer_name==''){
        return false;
    }else{
        return true;
    }
}
//重新开始游戏
function replayGameMc(){
    score = 0;
    speed=0;
    if(currentMap){
        gameMapCon.removeChild(currentMap);
        currentMap=null;
    }
    if(newMap){
        gameMapCon.removeChild(newMap);
        newMap=null;
    }
    //gameMapCon=null;

    if(paizi){
        paiziCon.removeChild(paizi);
        paizi=null;
    }
    //paiziCon=null;
    if(barrier){
        barrierCon.removeChild(barrier);
        barrier=null;
    }
    //barrierCon=null;

    distance = 0;//行驶的距离

    currentPaiziPoint = 0;//牌子数组指针
    oldPaiziPosition = 0;//前一个牌子位置
    paiziUnit=null;//牌子
    paiziCount = 0;//牌子总数

    currentMapArrPoint = 0;//牌子数组指针
    oldMapPosition = 0;
    mapUnit = 0;//地图
    mapCount = 0;//地图数组总数
    createGameMapCount = 0;//生成的地图总数

    currentBarrierPoint = 0;//障碍数组指针
    oldBarrierPosition = 0;//前一个障碍位置
    barrierUnit=null;//障碍
    barrierCount = 0;//障碍总数

    if(audio_bg){
        stage.removeChild(stage.getChildByName('btn_audio_bg'));
        audio_bg.pause();
        audio_bg.currentTime = 0.0;
    }

    clearInterval(gameInterval);
    isPause=true;
    iniGameMc();
}
//开始界面按钮
function iniGameBeginBtn() {
    if (main) {
        main.game_begin.btn_go.addEventListener('mousedown', btnMousedownHandle1);
        main.game_begin.btn_go.addEventListener('pressup', goUpHandle);
        //main.game_begin.btn_rule.addEventListener('mousedown', btnMousedownHandle);
        main.game_begin.btn_rule.addEventListener('pressup', ruleUpHandle);
        //main.game_begin.btn_prizeinfo.addEventListener('mousedown', btnMousedownHandle);
        main.game_begin.btn_prizeinfo.addEventListener('pressup', prizeinfoUpHandle);
    }
}

//启动
function startCar() {
    main.car.gotoAndPlay('startcar');
    audio_btn = getEl('music_audio_start');
    audio_btn.play();
    setTimeout('iniBgSound()',1000);
    isPause = false;
    if(checkPlatform()=='android-wx'){
        createjs.Ticker.setFPS(18);
    }
    //speed = initSpeed;
}
//游戏地图
function iniGameMap() {
    currentMap = eval('new lib.Road1();');
    currentMap.x = 0;
    currentMap.y = -1020;
    gameMapCon.addChild(currentMap);
    createGameMapCount++;
    //console.log('生成新地图'+createGameMapCount);
    //开始渲染
    gameInterval = setInterval('mapEnterFrameHandle()', 5);
}
//生成地图
function createGameMap(name, yy) {
    newMap = eval('new lib.' + name + '();');
    newMap.x = 0;
    newMap.y = -2100 + yy;
    //console.log('newMap.y='+newMap.y);
    gameMapCon.addChild(newMap);
    createGameMapCount++;
    //console.log('生成新地图'+createGameMapCount);
}
function removeGameMap() {
    gameMapCon.removeChild(currentMap);
    currentMap = newMap;
    newMap = null;
    //console.log('删除旧地图');
}


//初始化牌子
function iniPaizi() {
    paizi = eval('new lib.GamePaizi1();');
    paizi.x = 88;
    paizi.y = 80;

    paizi.name = 'GamePaizi1';
    paiziCon.addChild(paizi);
}
//生成牌子
function createPaizi(paizi_name) {
    paizi = eval('new lib.' + paizi_name + '();');
    paizi.x = 88;
    paizi.y = -171;

    paizi.name = paizi_name;
    paiziCon.addChild(paizi);
}

//生成障碍
function createBarrier(barrier_name){
    barrier = eval('new lib.' + barrier_name + '();');
    barrier.x = 0;
    barrier.y = -200;

    barrier.name = barrier_name;
    barrierCon.addChild(barrier);
}

//地图移动
function mapEnterFrameHandle() {
    if (!isPause) {
        if(speed<initSpeed){
            speed = speed + 0.01;
        }
        //地图滚动
        if (currentMap) {
            currentMap.y += speed;
            if (currentMap.y > 1080) {
                removeGameMap();
            }
        }
        if (newMap) {
            newMap.y += speed;
        }
        distance += speed;//累计速度即得到行驶的距离
        //根据行驶里程滚动地图
        mapUnit = mapUnitArray[currentMapArrPoint];
        //console.log(distance);
        if (distance - (oldMapPosition + mapUnit.interval) >= -100) {
            createGameMap(mapUnit.name, currentMap.y);
            //console.log('currentMap.y='+currentMap.y);
            //isPause=true;
            //distance=oldMapPosition+mapUnit.interval;
            oldMapPosition = oldMapPosition + mapUnit.interval;
            //console.log(distance);
            //判断游戏是否通关
            if (currentMapArrPoint < mapCount - 1) {
                currentMapArrPoint++;
            } else {
                //循环，永远不会结束
                currentMapArrPoint = 1;
            }
        }
        //判断是否到达目的地
        if (distance >= score * 50) {
            speed = speed - 0.05;
            if (speed <= 0.1) {
                isPause = true;
                clearInterval(gameInterval);
                if(checkPlatform()=='android-wx'){
                    createjs.Ticker.setFPS(30);
                }
                main.car.gotoAndPlay('stopcar');
                //gameover
                if(score==325){
                    setTimeout('showResultSuccessMc()',500);
                    //showResultSuccessMc();
                }else{
                    setTimeout('showLoseMc()',500);
                    //showLoseMc();
                }
            }
        }

        if(paizi){
            paizi.y += speed;
            if (paizi.y > 1080) {
                paiziCon.removeChild(paizi);
                paizi=null;
            }
        }
        //根据行驶里程出现牌子
        paiziUnit = paiziUnitArray[currentPaiziPoint];
        //计算距离上一个牌子的距离，当他等于牌子的interval时，即创建此牌子
        //oldPosition+paiziUnit.interval为检测点的位置
        if (distance - (oldPaiziPosition + paiziUnit.interval) >= -20) {
            createPaizi(paiziUnit.name);
            oldPaiziPosition = oldPaiziPosition + paiziUnit.interval;

            if (currentPaiziPoint < paiziCount - 1) {
                currentPaiziPoint++;
            }else {
                //循环，永远不会结束
                currentPaiziPoint = 1;
            }
        }

        if(barrier){
            barrier.y += speed;
            if (barrier.y > 1080) {
                barrierCon.removeChild(barrier);
                barrier=null;
            }
        }
        //根据行驶里程出现牌子
        barrierUnit = barrierUnitArray[currentBarrierPoint];
        //计算距离上一个障碍的距离，当他等于牌子的interval时，即创建此障碍
        //oldPosition+barrierUnit.interval为检测点的位置
        if (distance - (oldBarrierPosition + barrierUnit.interval) >= -20) {
            createBarrier(barrierUnit.name);
            //console.log('barrierUnit.name');
            oldBarrierPosition = oldBarrierPosition + barrierUnit.interval;
        }
    }
}
//显示游戏规则界面
function showRuleMc() {
    if (popMc) {
        exportRoot.removeChild(popMc);
        popMc = null;
    }
    popMc = new lib.PopRuleMc();
    exportRoot.addChild(popMc);
    popMc.gotoAndPlay(1);
    popMc.btn_close.addEventListener('click', closePopClickHandle1);
}
//显示奖品界面
function showPrizeinfoMc() {
    if (popMc) {
        exportRoot.removeChild(popMc);
        popMc = null;
    }
    popMc = new lib.PopPrizeInfoMc();
    exportRoot.addChild(popMc);
    popMc.gotoAndPlay(1);
    popMc.btn_close.addEventListener('click', closePopClickHandle1);
}
//显示游戏失败界面
function showLoseMc(){
    if (popMc) {
        exportRoot.removeChild(popMc);
        popMc = null;
    }
    popMc = new lib.PopLoseMc();
    if(score>325){
        changeShareTxt('大马力是我的人生信条，然并卵，现在我只想要好礼。');
        popMc.con.msg.text='开猛了，超过了'+(score-325)+'km！\n'+closer_percent+'% 的人比你更接近325km，\n再加把劲！';
    }
    if(score<325){
        changeShareTxt('我达不到的位置，你能到么？为了好礼你也是什么都做得出来的。');
        popMc.con.msg.text='年轻人你的能量呢，还差'+(325-score)+'km！\n'+closer_percent+'% 的人比你更接近325km，\n再加把劲！';
    }
    exportRoot.addChild(popMc);
    popMc.gotoAndPlay(1);
    popMc.btn_close.addEventListener('click', closePopClickHandle);
    //popMc.con.btn_replay.addEventListener('mousedown',btnMousedownHandle);
    popMc.con.btn_replay.addEventListener('pressup',replayUpHandle);
    //popMc.con.btn_share.addEventListener('mousedown',btnMousedownHandle);
    popMc.con.btn_share.addEventListener('pressup',shareUpHandle);
}
//显示游戏成功界面
function showResultSuccessMc(){
    if (popMc) {
        exportRoot.removeChild(popMc);
        popMc = null;
    }
    popMc = new lib.PopResultSuccessMc();
    exportRoot.addChild(popMc);
    popMc.gotoAndPlay(1);
    popMc.btn_close.addEventListener('click', closePopClickHandle);
    //popMc.con.btn_luck.addEventListener('mousedown',btnMousedownHandle);
    popMc.con.btn_luck.addEventListener('pressup',showLuckUpHandle);
    changeShareTxt('我的车技已超神，超过96%玩家，不服进来试一试。');
}
//显示抽奖界面
function showLuckMc() {
    if (popMc) {
        exportRoot.removeChild(popMc);
        popMc = null;
    }
    popMc = new lib.PopLuckMc();
    exportRoot.addChild(popMc);
    popMc.gotoAndPlay(1);
    popMc.btn_close.addEventListener('click', closePopClickHandle);
    popMc.con.baoxiang1.addEventListener('click',luckUpHandle);
    popMc.con.baoxiang2.addEventListener('click',luckUpHandle);
    popMc.con.baoxiang3.addEventListener('click',luckUpHandle);
    popMc.con.baoxiang4.addEventListener('click',luckUpHandle);
    popMc.con.baoxiang5.addEventListener('click',luckUpHandle);
    popMc.con.baoxiang6.addEventListener('click',luckUpHandle);
}

//显示中奖界面
function showWinningMc(prize_name){
    if (popMc) {
        exportRoot.removeChild(popMc);
        popMc = null;
    }
    popMc = new lib.PopWinningMc();
    popMc.con.msg.text='你拿到了'+prize_name;
    exportRoot.addChild(popMc);
    popMc.gotoAndPlay(1);
    popMc.btn_close.addEventListener('click', closePopClickHandle);
    //popMc.con.btn_form.addEventListener('mousedown',btnMousedownHandle);
    popMc.con.btn_form.addEventListener('pressup',showInfoFormUpHandle);
}
//显示中汽车模型界面
function showWinningMc1(prize_name){
    if (popMc) {
        exportRoot.removeChild(popMc);
        popMc = null;
    }
    popMc = new lib.PopWinningMc1();
    popMc.con.msg.text='你拿到了'+prize_name;
    exportRoot.addChild(popMc);
    popMc.gotoAndPlay(1);
    popMc.btn_close.addEventListener('click', closePopClickHandle);
    //popMc.con.btn_form.addEventListener('mousedown',btnMousedownHandle);
    popMc.con.btn_form.addEventListener('pressup',showInfoFormUpHandle);
}
//显示未中奖界面
function showNoPrizeMc(){
    if (popMc) {
        exportRoot.removeChild(popMc);
        popMc = null;
    }
    popMc = new lib.PopLoseMc();
    popMc.con.msg.text='很遗憾\n最悲伤的事就是选错了箱子，\n别把悲伤留给自己，再玩一次吧！';
    exportRoot.addChild(popMc);
    popMc.gotoAndPlay(1);
    popMc.btn_close.addEventListener('click', closePopClickHandle);
    //popMc.con.btn_replay.addEventListener('mousedown',btnMousedownHandle);
    popMc.con.btn_replay.addEventListener('pressup',replayUpHandle);
    //popMc.con.btn_share.addEventListener('mousedown',btnMousedownHandle);
    popMc.con.btn_share.addEventListener('pressup',shareUpHandle);
}

//显示中奖用户列表
function showWinningListMc() {
    if (popMc) {
        exportRoot.removeChild(popMc);
        popMc = null;
    }
    popMc = new lib.PopWinningListMc();
    //更新数据
    //alert(returnWinningList);
    var wxname = '';
    var prizename = '';

    var count = returnWinningList.length;
    for (var i = 0; i < count; i++) {
        wxname += returnWinningList[i].nickname.substr(0,7) + '\n';
        prizename += returnWinningList[i].gift_name + '\n';
    }
    popMc.con.winninglist.con.wxname.text = wxname;
    popMc.con.winninglist.con.prizename.text = prizename;

    scrollY = ScrollY.init(popMc.con.winninglist.con, popMc.con.winninglist.scrollBar, 385, 390, 288, 288 + 390);
    scrollY.addEvent();

    exportRoot.addChild(popMc);
    popMc.gotoAndPlay(1);
    popMc.btn_close.addEventListener('click', closePopClickHandle);
    //popMc.con.btn_replay.addEventListener('mousedown',btnMousedownHandle);
    popMc.con.btn_replay.addEventListener('pressup',replayUpHandle);
    //popMc.con.btn_share.addEventListener('mousedown',btnMousedownHandle);
    popMc.con.btn_share.addEventListener('pressup',shareUpHandle);
}


//显示中奖信息提交界面
function showInfoForm() {
    getEl('infoForm').style.display = 'block';
}



//公用按钮按下事件
function btnMousedownHandle(evt) {
    if (checkPointID(evt)) {
        createjs.Tween.get(evt.currentTarget).to({scaleX: 0.9, scaleY: 0.9}, 100);
    }
}
function btnMousedownHandle1(evt) {
    if (checkPointID(evt)) {
        createjs.Tween.get(evt.currentTarget).to({scaleX: 0.9, scaleY: 0.9}, 100);
        main.game_begin.tips_hand.visible = false;
        main.game_begin.powerbar.gotoAndPlay(1);
        main.car.gotoAndPlay('stopcar');

        audio_btn = getEl('music_audio_go');
        audio_btn.play();
    }
}
//开始按钮
function goUpHandle(evt) {
    if (checkPointID(evt)) {
        createjs.Tween.get(evt.currentTarget).to({scaleX: 1, scaleY: 1}, 100);
        main.game_begin.powerbar.stop();

        score = Math.floor((250 - Math.floor(main.game_begin.powerbar.power_point.y)) / 250 * 400);
        if(score>=320 && score<=330){
            score=325;
        }
        console.log('score=' + score);
        createjs.Tween.get(main.game_begin).to({alpha: 0}, 500);
        if(testNow){
            startCar();
        }else{
            submitRunResult();//将成绩提交后台，返回安全码
        }

    }
}
//游戏规则
function ruleUpHandle(evt) {
    if (checkPointID(evt)) {
        showRuleMc();
    }
}
//奖品信息
function prizeinfoUpHandle(evt) {
    if (checkPointID(evt)) {
        showPrizeinfoMc();
    }
}

//抽奖界面
function showLuckUpHandle(evt) {
    if (checkPointID(evt)) {
        showLuckMc();
    }
}
//中奖名单
function showWinningListUpHandle(evt) {
    if (checkPointID(evt)) {
        getLotteryCustomerList();
    }
}
//提交信息表单
function showInfoFormUpHandle(evt) {
    if (checkPointID(evt)) {
        showInfoForm();
    }
}

//开宝箱
function luckUpHandle(evt) {
    if (checkPointID(evt)) {
        console.log('抽奖');
        evt.currentTarget.gotoAndPlay(1);

        if(!testNow){
            setTimeout('drawnLottery()',1000);
        }
    }
}
function shareUpHandle(evt) {
    if (checkPointID(evt)) {
        showShareMc();
    }
}
function showShareMc() {
    if(shareTips){
        exportRoot.removeChild(shareTips);
        shareTips=null;
    }
    shareTips=new lib.ShareMc();
    exportRoot.addChild(shareTips);
    shareTips.gotoAndPlay(1);
    shareTips.addEventListener('click',closeShareTipsClickHandle);
}
function closeShareTipsClickHandle(evt){
    if (checkPointID(evt)) {
        if (shareTips) {
            exportRoot.removeChild(shareTips);
            shareTips = null;
        }
    }
}
function replayUpHandle(evt) {
    if (checkPointID(evt)) {
        location.reload();
    }
}

function closePopClickHandle(evt) {
    if (checkPointID(evt)) {
        if (popMc) {
            exportRoot.removeChild(popMc);
            popMc = null;
            replayGameMc();
        }
    }
}
function closePopClickHandle1(evt) {
    if (checkPointID(evt)) {
        if (popMc) {
            exportRoot.removeChild(popMc);
            popMc = null;
        }
    }
}
//控制ui自适应
function iniUiScale() {
    var p = document.documentElement.clientWidth / 640;
    getEl('infoForm').style.zoom = p;
}


//提交数据--------------------------------
//存储用户信息
function initCustomer() {
    var params = [];
    params.push('openid=' + openid);
    params.push('openid_md5=' + openid_md5);
    params.push('nickname=' + nickname);
    params.push('sex=' + sex);
    params.push('province=' + province);
    params.push('city=' + city);
    params.push('country=' + country);
    params.push('headimgurl=' + headimgurl);
    console.log(params);
    sendRequest('http://hbweixin.twomi.cn/api_hb_game/initCustomer', function (res) {
        //alert(res.response);
        res = eval('(' + res.response + ')');
        if (res.success) {
            returnMyCustomer = res.addon.customer;
            initCjs();
        } else {
            alert(res.detail);
        }
    }, params.join('&'));
}

//提交跑的距离
function submitRunResult() {
    var params = [];
    params.push('distance=' + score);
    sendRequest('http://hbweixin.twomi.cn/api_hb_game/submitRunResult', function (res) {
        //alert(res.response);
        res = eval('(' + res.response + ')');
        if (res.success) {
            salt=res.addon.salt;
            closer_percent=res.addon.closer_percent;
            startCar();//返回安全码后，才开始启动汽车
        } else {
            alert(res.detail);
        }
    }, params.join('&'));
}

//抽奖
function drawnLottery() {
    var params = [];
    params.push('salt=' + salt);
    sendRequest('http://hbweixin.twomi.cn/api_hb_game/drawnLottery', function (res) {
        //alert(res.response);
        res = eval('(' + res.response + ')');
        if (res.success) {
            returnPrizeObj=res.addon;
            //gift_type,gift_name
            if(parseInt(returnPrizeObj.gift_type)==0){
                showNoPrizeMc();
            }else{
                if(parseInt(returnPrizeObj.gift_type)==1){
                    showWinningMc1(returnPrizeObj.gift_name);
                }else{
                    showWinningMc(returnPrizeObj.gift_name);
                }
            }
        } else {
            alert(res.detail);
        }
    }, params.join('&'));
}

//提交个人信息
function submitForm(frm) {
    var params = [];
    var email_reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    for (var i = 0, len = frm.elements.length; i < len; i++) {
        el = frm.elements[i];
        if (el.name == 'customer_name' && el.value == '') {
            alert('请输入你的姓名!');
            return false;
        }
        if (el.name == 'customer_phone' && !(/^1(3|5|8)\d{9}$/.test(el.value))) {
            alert('请输入正确的手机号码!');
            return false;
        }
        if (el.name == 'customer_address' && el.value == '') {
            alert('请输入正确的收货地址!');
            return false;
        }
        if (el.name && el.value !== '' && (el.type != 'radio' || el.checked)) {
            params.push(el.name + '=' + el.value);
        }
    }
    console.log(params);
    sendRequest(frm.action, function (res) {
        res = eval('(' + res.response + ')');
        //alert(res.detail);
        if (res.success) {
            alert('信息提交成功，在家等待奖品上门吧~');
            getEl('infoForm').style.display = 'none';
            getLotteryCustomerList();
        } else {
            alert(res.detail);
        }
    }, params.join('&'));
}
//得到中奖列表
function getLotteryCustomerList() {
    var params = [];
    sendRequest('http://hbweixin.twomi.cn/api_hb_game/getLotteryCustomerList', function (res) {
        //alert(res.response);
        res = eval('(' + res.response + ')');
        if (res.success) {
            returnWinningList = res.items;
            showWinningListMc();
        } else {
            alert(res.detail);
        }
    }, params.join('&'));
}
//分享成功
function shareAction(){
    if(shareTips){
        exportRoot.removeChild(shareTips);
        shareTips=null;
    }
}
//----------终端检测------
function checkDevice() {
    if (!navigator.userAgent.match(/mobile/i)) {
        //alert("当前设备为pc");
        isWap = false;
    } else {
        //alert("当前设备为移动");
        isWap = true;
    }
}
function checkPointID(evt) {
    if (isWap) {
        if (evt.pointerID != -1) {
            return true;
        } else {
            return false;
        }
    } else {
        if (evt.pointerID == -1) {
            return true;
        } else {
            return false;
        }
    }
}
//获取dom
function getEl(id) {
    return document.getElementById(id);
}
function checkPlatform() {
    if (/android/i.test(navigator.userAgent) && /MicroMessenger/i.test(navigator.userAgent)) {
        return 'android-wx';
    }
    if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent) && /MicroMessenger/i.test(navigator.userAgent)) {
        return 'ios-wx';
    }
    return false;
}
//更新分享信息
function changeShareTxt(txt){
    shareTitle=txt;
    //shareDesc='';
    iniWx();
}


//--------------分享-------------
var shareLink = 'http://hbweixin.twomi.cn/2016/2016_LingDong325Game/index.html';
var shareImg = 'http://hbweixin.twomi.cn/2016/2016_LingDong325Game/images/wxShare.jpg';
var shareTitle = '疯狂325';
var shareDesc = '精美汽车车模，等你蓄势待发！';
function iniWx() {
    wx.config({
        debug: false,
        appId: signPackage.appId,
        timestamp: parseInt(signPackage.timestamp),
        nonceStr: signPackage.nonceStr,
        signature: signPackage.signature,
        jsApiList: [
            'checkJsApi',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo'
        ]
    });
    //config接口处理成功后
    wx.ready(function () {
        // 1 判断当前版本是否支持指定 JS 接口，支持批量判断
        wx.checkJsApi({
            jsApiList: [
                'getNetworkType',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo'
            ],
            success: function (res) {
                //alert(JSON.stringify(res));
                //网络+分享
                checkResult = eval('(' + JSON.stringify(res) + ')');
                checkResult = checkResult.checkResult;
                if (checkResult.getNetworkType) {
                    getNetworkType();
                }
                if (checkResult.onMenuShareTimeline) {
                    onMenuShareTimeline();
                }
                if (checkResult.onMenuShareAppMessage) {
                    onMenuShareAppMessage();
                }
                if (checkResult.onMenuShareQQ) {
                    onMenuShareQQ();
                }
                if (checkResult.onMenuShareWeibo) {
                    onMenuShareWeibo();
                }
            }
        });
    });
    //错误
    wx.error(function (res) {
        alert(res.errMsg);
    });
}
//------------------------------以下为常规接口-------------------------
//配置检测网络接口
function getNetworkType() {
    wx.getNetworkType({
        success: function (res) {
            console.log(res.networkType);
        },
        fail: function (res) {
            console.log(JSON.stringify(res));
        }
    });
}
//注册获取“发送给朋友”状态事件
function onMenuShareAppMessage() {
    wx.onMenuShareAppMessage({
        title: shareTitle,
        desc: shareDesc,
        link: shareLink,
        imgUrl: shareImg,
        trigger: function (res) {
            //alert('用户点击发送给朋友');
        },
        success: function (res) {
            //alert('已分享');
            shareAction();
        },
        cancel: function (res) {
            //alert('已取消');
        },
        fail: function (res) {
            //alert(JSON.stringify(res));
        }
    });
}
//注册获取“分享到朋友圈”状态事件
function onMenuShareTimeline() {
    wx.onMenuShareTimeline({
        title: shareTitle,
        link: shareLink,
        imgUrl: shareImg,
        trigger: function (res) {
            //alert('用户点击分享到朋友圈');
        },
        success: function (res) {
            //alert('已分享');
            shareAction();
        },
        cancel: function (res) {
            //alert('已取消');
        },
        fail: function (res) {
            //alert(JSON.stringify(res));
        }
    });
}
//注册获取“分享到 QQ”状态事件
function onMenuShareQQ() {
    wx.onMenuShareQQ({
        title: shareTitle,
        desc: shareDesc,
        link: shareLink,
        imgUrl: shareImg,
        trigger: function (res) {
            //alert('用户点击分享到QQ');
        },
        complete: function (res) {
            //alert(JSON.stringify(res));
        },
        success: function (res) {
            //alert('已分享');
        },
        cancel: function (res) {
            //alert('已取消');
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    });
}
//注册获取“分享到微博”状态事件
function onMenuShareWeibo() {
    wx.onMenuShareWeibo({
        title: shareTitle,
        desc: shareDesc,
        link: shareLink,
        imgUrl: shareImg,
        trigger: function (res) {
            //alert('用户点击分享到微博');
        },
        complete: function (res) {
            //alert(JSON.stringify(res));
        },
        success: function (res) {
            //alert('已分享');
        },
        cancel: function (res) {
            //alert('已取消');
        },
        fail: function (res) {
            //alert(JSON.stringify(res));
        }
    });
}